var express = require('express');
var router = express.Router();

const fs = require('fs');
const path = require('path');
const mime = require("mime");

const configMsg = require("./config.json");

let codeMode = process.env.NODE_ENV || 'develop';

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.post('/login', function(req, res, next) {
  let username = req.body.username;
  let pwd = req.body.password;
  if (!username || !pwd) {
    res.status(400).send({
      msg: 'Login Faild~! Please check the username or password~!'
    });
    return;
  }

  if (configMsg.username === username && configMsg.password === pwd) {
    res.send({
      msg: "Login success!"
    });
  } else {
    res.status(401).send({
      msg: 'Login Faild~! username or password ERROR!'
    });
  }
});

router.get('/fileList', function(req, res, next) {
  let type = req.query.type;
  let jsonFiles = [];
  if (!type) {
    res.status(400).send({
      msg: 'Params ERROR!'
    });
    return;
  }
  
  let filePath = '';
  let fPath = '';
  if (codeMode == 'develop') {
    filePath = path.join(__dirname, `/public/media/${type}`)
  } else {
    filePath = `./public/media/${type}`;
  }
  
  if (!fs.existsSync(filePath)) {
    res.status(500).send({
      msg: 'The directory is not exit~!'
    })
    return
  }
  let files = fs.readdirSync(filePath);
  
  files.forEach(function (item, index) {
    if (item == '.keep') {
      return;
    }
    let fPath = '';
    if (codeMode == 'develop') {
      fPath = path.join(__dirname, `/public/media/${type}/${item}`)
    } else {
      fPath = `${filePath}/${item}`;
    }
    let stat = fs.statSync(fPath);
    if (stat.isFile() === true) { 
      jsonFiles.push({
        filetype: type,
        filename: item,
        filesize: stat.size,
        birthtime: stat.birthtime,
        cType: mime.lookup(filePath)
      });
    }
  });
  res.send(jsonFiles);
});

router.get("/media", function(req, res, next) {
  let type = req.query.type;
  let filename = req.query.filename;
  if (!type || !filename) {
    req.status(400).send({
      msg: 'Params ERROR~!'
    })
    return
  }

  let filePath = '';  
  if (codeMode == 'develop') {
    filePath = path.join(__dirname, `/public/media/${type}/${filename}`)
  } else {
    filePath = `./public/media/${type}/${filename}`;
  }
  let stat = fs.statSync(filePath);
  let fileSize = stat.size;
  let range = req.headers.range;

  if (range) {
    //有range头才使用206状态码
    let parts = range.replace(/bytes=/, "").split("-");
    let start = parseInt(parts[0], 10);
    let end = parts[1] ? parseInt(parts[1], 10) : start + 999999;

    // end 在最后取值为 fileSize - 1 
    end = end > fileSize - 1 ? fileSize - 1 : end;

    let chunksize = (end - start) + 1;
    let file = fs.createReadStream(filePath, { start, end });
    let head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': mime.lookup(filePath),
    };
    res.writeHead(206, head);
    file.pipe(res);
  } else {
    let head = {
      'Content-Length': fileSize,
      'Content-Type': mime.lookup(filePath),
    };
    res.writeHead(200, head);
    fs.createReadStream(filePath).pipe(res);
  }
})

module.exports = router;
